﻿using ERPWinFormWork.Produce.Domain;
using ERPWinFormWork.Produce.ErrorCode;
using ERPWinFormWork.Product;
using ERPWinFormWork.Sales.DTO.Output;
using Newtonsoft.Json;

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.AxHost;

namespace ERPWinFormWork.Produce
{
    public partial class CreateProduction_Plan : Form
    {
        Production_PlanForm form1 = new Production_PlanForm();
        private ApiClient _apiClient;
        private static readonly HttpClient _httpClient = new HttpClient();
        private int? _editId; // 编辑时的主键ID
        // 后端 API 接口地址，可根据实际情况调整
        public CreateProduction_Plan(Production_PlanForm form1)
        {
            InitializeComponent();
            _apiClient = new ApiClient(AppConfig.ApiBaseUrl);
         this.form1 = form1;
            LoadcboSource_TypeData();
            GetProductSelect();
            GetSales_Ticket();

            this.Load += CreateProduction_Plan_Load; // Add Load event for beautification
        }

        // 编辑模式构造：传入要编辑的ID
        public CreateProduction_Plan(Production_PlanForm form1, int editId) : this(form1)
        {
            _editId = editId;
            // 加载详情并回填
            this.Shown += async (s, e) => await LoadDetailAndFillAsync();
            this.Text = "编辑生产计划";
        }

        // Add Load event handler for applying styles
        private void CreateProduction_Plan_Load(object sender, EventArgs e)
        {
            // Set form properties
            this.BackColor = System.Drawing.Color.FromArgb(240, 240, 240); // Light gray background for modern look
            this.Text = "计划信息"; // Meaningful title
            this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 20F);

            // Beautify labels (assuming labels are label1 to label16)
            foreach (Control ctrl in this.Controls)
            {
                if (ctrl is Label)
                {
                    ctrl.Font = new System.Drawing.Font("Segoe UI", 10F);
                }
            }
            label11.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold); // Title label

            // Beautify textboxes
            foreach (Control ctrl in this.Controls)
            {
                if (ctrl is TextBox && ctrl != txtNotes)
                {
                    ctrl.Font = new System.Drawing.Font("Segoe UI", 10F);
                    ((TextBox)ctrl).BorderStyle = BorderStyle.FixedSingle;
                }
            }

            // Beautify comboboxes
            cboSourceType.Font = new System.Drawing.Font("Segoe UI", 10F);
            cboProduct_Id.Font = new System.Drawing.Font("Segoe UI", 10F);
            cboOrder_Number.Font = new System.Drawing.Font("Segoe UI", 10F);

            // Beautify DateTimePickers
            dtpStart_Time.Font = new System.Drawing.Font("Segoe UI", 10F);
            dtpCompletion_Time.Font = new System.Drawing.Font("Segoe UI", 10F);
            dtpRequirement_Date.Font = new System.Drawing.Font("Segoe UI", 10F);

            // Beautify SkinTextBox (notes)
            txtNotes.Font = new System.Drawing.Font("Segoe UI", 10F);

            // Beautify submit button
            btncreatesubmit.BackColor = System.Drawing.Color.FromArgb(0, 122, 204); // Blue
            btncreatesubmit.ForeColor = System.Drawing.Color.White;
            btncreatesubmit.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            btncreatesubmit.FlatAppearance.BorderSize = 0;
            btncreatesubmit.Font = new System.Drawing.Font("Segoe UI", 10F, System.Drawing.FontStyle.Bold);
        }

        private async Task LoadDetailAndFillAsync()
        {
            if (!_editId.HasValue) return;
            try
            {
                var parameters = new Dictionary<string, string> { { "Id", _editId.Value.ToString() } };
                var response = await _apiClient.GetAsync<ApiResponse<List<CreateProduction_PlanModel>>>(
                    endpoint: "Production_Plan/Production_PlanShowHandle",
                    parameters: parameters
                );
                if (response != null && response.code == 200 && response.pageData != null && response.pageData.Count > 0)
                {
                    var m = response.pageData[0];
                    // 回填基础字段
                    txtPlanNumber.Text = m.Plan_Number ?? string.Empty;
                    txtPlanName.Text = m.Plan_Name ?? string.Empty;
                    txtQuantity_Orders.Text = m.Quantity_Orders.ToString();
                    txtPlanned_quantity.Text = m.Planned_quantity.ToString();
                    cboSourceType.Text = m.Source_Type ?? string.Empty;
                    cboOrder_Number.Text = m.Order_Number ?? string.Empty;

                    // 产品下拉：按ID选中
                    if (m.Product_Id > 0)
                    {
                        cboProduct_Id.SelectedValue = m.Product_Id;
                    }

                    // 日期
                    dtpStart_Time.Value = m.Start_Time;
                    dtpCompletion_Time.Value = m.Completion_Time;
                    dtpRequirement_Date.Value = m.Requirement_Date;

                    // 备注及联动显示字段
                    txtNotes.Text = m.Notes ?? string.Empty;
                  
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载详情失败: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void textBox10_TextChanged(object sender, EventArgs e)
        {

        }
        public class CreateProduction_PlanModel
        {
            /// <summary>
            /// 计划编号
            /// </summary>
            public string Plan_Number { get; set; }
            /// <summary>
            /// 计划名称
            /// </summary>
            public string Plan_Name { get; set; }
            /// <summary>
            /// 工单数量
            /// </summary>
            public int Quantity_Orders { get; set; }
            /// <summary>
            /// 来源类型
            /// </summary>
            public string Source_Type { get; set; }
            /// <summary>
            /// 订单编号
            /// </summary>
            public string Order_Number { get; set; }
            /// <summary>
            /// 产品ID
            /// </summary>
            public int Product_Id { get; set; }
            /// <summary>
            /// 计划数量
            /// </summary>
            public int Planned_quantity { get; set; }
            /// <summary>
            /// 计划开工时间
            /// </summary>
            public DateTime Start_Time { get; set; }
            /// <summary>
            /// 计划完工时间
            /// </summary>
            public DateTime Completion_Time { get; set; }
            /// <summary>
            /// 需求日期
            /// </summary>
            public DateTime Requirement_Date { get; set; }
            /// <summary>
            /// 状态
            /// </summary>
            public int State { get; set; }
            /// <summary>
            /// 备注
            /// </summary>
            public string Notes { get; set; }
        }

        // 更新用，包含主键
        public class UpdateProduction_PlanModel : CreateProduction_PlanModel
        {
            public int Id { get; set; }
        }

        private async void btncreatesubmit_Click(object sender, EventArgs e)
        {
            // 构建基础请求体
            int productId = 0;
            if (cboProduct_Id.SelectedValue != null)
            {
                int.TryParse(cboProduct_Id.SelectedValue.ToString(), out productId);
            }

            var baseModel = new CreateProduction_PlanModel
            {
                Plan_Number = txtPlanNumber.Text.Trim(),
                Plan_Name = txtPlanName.Text.Trim(),
                Source_Type = cboSourceType.Text.Trim(),
                Order_Number = cboOrder_Number.Text.Trim(),
                Product_Id = productId,
                Start_Time = dtpStart_Time.Value,
                Completion_Time = dtpCompletion_Time.Value,
                Planned_quantity = int.TryParse(txtPlanned_quantity.Text.Trim(), out int quantity) ? quantity : 0,
                Quantity_Orders = int.TryParse(txtQuantity_Orders.Text.Trim(), out int orders) ? orders : 0,
                Requirement_Date = dtpRequirement_Date.Value,
                Notes = txtNotes.Text.Trim(),
                State = 1
            };

            if (_editId.HasValue)
            {
                // 更新
                var updateModel = new UpdateProduction_PlanModel
                {
                    Id = _editId.Value,
                    Plan_Number = baseModel.Plan_Number,
                    Plan_Name = baseModel.Plan_Name,
                    Quantity_Orders = baseModel.Quantity_Orders,
                    Source_Type = baseModel.Source_Type,
                    Order_Number = baseModel.Order_Number,
                    Product_Id = baseModel.Product_Id,
                    Planned_quantity = baseModel.Planned_quantity,
                    Start_Time = baseModel.Start_Time,
                    Completion_Time = baseModel.Completion_Time,
                    Requirement_Date = baseModel.Requirement_Date,
                    State = baseModel.State,
                    Notes = baseModel.Notes
                };

                var respUpdate = await _apiClient.PostAsync<UpdateProduction_PlanModel, ApiResponse<string>>(
                    endpoint: "Production_Plan/UpdateProduction_PlanHandle",
                    data: updateModel
                );
                if (respUpdate != null && respUpdate.code == 200)
                {
                    MessageBox.Show("保存修改成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    form1.GetData();
                    this.Close();
                    return;
                }
                MessageBox.Show("保存修改失败: " + (respUpdate?.msg ?? ""), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                // 新增
                var response = await _apiClient.PostAsync<CreateProduction_PlanModel, ApiResponse<string>>(
                    endpoint: "Production_Plan/CreateProduction_PlanHandle",
                    data: baseModel
                );
                if (response.code == 200)
                {
                    MessageBox.Show("生产计划添加成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    ClearControls();
                    form1.GetData();
                    this.Close();
                }
                else
                {
                    MessageBox.Show("新增失败: " + (response?.msg ?? ""), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }



        }


        // 清空窗体控件内容的方法，按需使用
        private void ClearControls()
        {
            txtPlanNumber.Clear();
            txtPlanName.Clear();
            cboSourceType.SelectedIndex = -1;
            cboProduct_Id.SelectedIndex = -1;
            cboOrder_Number.SelectedIndex = -1;
            txtSpecification.Clear();
            txtUnit.Clear();
            dtpStart_Time.Value = DateTime.Now;
            dtpCompletion_Time.Value = DateTime.Now;
            txtPlanned_quantity.Clear();
            txtQuantity_Orders.Clear();
            dtpRequirement_Date.Value = DateTime.Now;
            txtNotes.Text.Clone();
        }

        private void LoadcboSource_TypeData()
        {
            // 模拟一个数据源，这里是简单的字符串列表，实际可从数据库等获取
            List<string> addressList = new List<string>()
            {
                "销售订单",
                "库存备货",
                "其他",
            };

            // 清空ComboBox原有项（可选，避免重复添加）
            cboSourceType.Items.Clear();
            // 将数据源的数据添加到ComboBox中
            cboSourceType.Items.AddRange(addressList.ToArray());

            // 可选：设置默认选中项，比如选第一个
            if (cboSourceType.Items.Count > 0)
            {
                cboSourceType.SelectedIndex = -1;
            }
        }

        private void cboSourceType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboSourceType.SelectedItem != null)
            {
                string selectedAddress = cboSourceType.SelectedItem.ToString();
                // MessageBox.Show($"你选择的地址是：{selectedAddress}");
            }
           
        }
        private async void GetProductSelect()
        {
            var response = await _apiClient.GetAsync<ApiResponse<List<ProductModel>>>(
                    endpoint: "Production_Plan/GetProductHandle"
                );
            if (response != null)
            {
                cboProduct_Id.DataSource = response.pageData;
                cboProduct_Id.DisplayMember = "product_Name";//指定显示的字段
                cboProduct_Id.ValueMember = "id";//绑定id属性
            }
        }
        private async void GetSales_Ticket()
        {
            var response = await _apiClient.GetAsync<ApiResponse<List<Sales_Ticket>>>(
                    endpoint: "Production_Plan/Sales_TicketHandle"
                );
            if (response != null)
            {
                cboOrder_Number.DataSource = response.pageData;
                cboOrder_Number.DisplayMember = "sales_Number";//指定显示的字段
                cboOrder_Number.ValueMember = "sales_Number";//绑定id属性
            }
        }
        private void cboProduct_Id_SelectedIndexChanged(object sender, EventArgs e)
        {
            var selectedProduct = cboProduct_Id.SelectedItem as ProductModel;
            if (selectedProduct != null)
            {
                txtProductNumber.Text = selectedProduct.Product_Number ?? "";
                txtSpecification.Text = selectedProduct.Specification ?? "";
                txtProductType.Text = selectedProduct.Finished_Type ?? "";
                txtUnit.Text = selectedProduct.Unit ?? "";
            }
            else
            {
                txtProductNumber.Text = "";
                txtSpecification.Text = "";
                txtProductType.Text = "";
            }
        }

        private void cboOrder_Number_SelectedIndexChanged(object sender, EventArgs e)
        {
           
        }
    }
}
